<template>
  <MdPreview
    previewTheme="github"
    :editorId="editorId"
    :modelValue="content"
    style="padding: 0px; height: 60vh"
  />
</template>

<script setup lang="ts">
import { MdPreview } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import "md-editor-v3/lib/preview.css";
import warningIcon from "@/assets/img/svg/warning.svg";
import errorIcon from "@/assets/img/svg/error.svg";
import mingcute from "@/assets/img/svg/mingcute.svg";
import { onMounted, ref } from "vue";

const editorId = "preview-only";
const content = ref("");
const contentList = ref([
  {
    code: "```Markdown\r\n ==落日西沉，炊烟袅袅。== \r\n```",
    md: "==落日西沉，炊烟袅袅。==",
  },
  {
    code: "```Markdown\r\n ||你知道的太多了|| \r\n```",
    md: "||你知道的太多了||",
  },
  {
    code:
      "```Markdown\r\n Polaris [跳转naiveui](https://www.naiveui.com/zh-CN/os-theme) \r\n```",
    md: "Polaris [跳转naiveui](https://www.naiveui.com/zh-CN/os-theme)",
  },
  {
    code: "```Markdown\r\n ::: warning\r\n warning\r\n ::: \r\n```",
    md: "::: warning\r\n warning\r\n :::\r\n",
  },
  {
    code: "```Markdown\r\n ::: error\r\n error\r\n ::: \r\n```",
    md: "::: error\r\n error\r\n :::\r\n",
  },
  {
    code:
      "```Markdown\r\n Polaris-link [跳转naiveui](https://www.naiveui.com/zh-CN/os-theme) \r\n```",
    md: "Polaris-link [跳转naiveui](https://www.naiveui.com/zh-CN/os-theme)",
  },
]);

onMounted(() => {
  contentList.value.forEach((d) => {
    content.value += d.code + "\r\n";
    content.value += customMarkdownParser(d.md) + "\r\n";
  });
  console.log(content.value);
});
const customMarkdownParser = (input) => {
  const patterns = [
    {
      regex: /::: (\w+)\s+(.+?)\s+:::/g,
      replacement: (match, type, content) =>
        `<div class='${type} block'><iframe src='${
          type == "error" ? errorIcon : warningIcon
        }'></iframe>${content}</div>`,
      // `<div class='${type}-block'><img src="${warningIcon}" alt="icon" style="filter: invert(40%) sepia(100%) saturate(1000%) hue-rotate(120deg);color:rgb(245, 158, 11);" />${content}</div>`,
    },
    {
      regex: /\|\|(.+?)\|\|/g,
      replacement: (match, type, content) =>
        `<span title='你知道到太多了' class='p-span-tag'>${type}</span>`,
    },
    {
      regex: /==(.+?)==/g,
      replacement: (match, lang, content) =>
        `<mark class='mark'><span class='mark-span rounded-md'>${lang}</span></mark>`,
    },
    {
      regex: /Polaris \[(.*?)\]\((.*?)\)/g,
      replacement: (match, lang, content) =>
        `<span style="display: inline-block;text-indent: 0em;"><a href="${content}" target="_blank" class='hover-link' style='text-decoration: none;'>${lang}</a><img style='width:17px;vertical-align: sub;pointer-events: none;' src='${mingcute}'></img><span class='p-a-span'>${content}</span></span>`,
      // `<div><a href="${content}" target="_blank" class='hover-link' style='text-decoration: none;'>${lang}</a><img style='width:17px;vertical-align: sub;pointer-events: none;' src='${mingcute}'></img><div class='p-a-div'>${content}</div></div>`,
    },
    {
      regex: /Polaris-link \[(.*?)\]\((.*?)\)/g,
      replacement:  (match, lang, content) => {
        // const faviconUrl = await getFavicon(content);
        // console.log(faviconUrl);
        return ` <article>
              <a
                href="${content}"
                target="_blank"
                class="card-link"
              >${lang}</a>
               <img src="https://www.naiveui.com/favicon.ico" alt="Favicon" />
          </article>`;
      },
    },
    // 可以继续添加其他自定义语法
  ];
  let result = input;

  patterns.forEach((pattern) => {
    result = result.replace(pattern.regex, pattern.replacement);
  });

  return result;
};

// 这个函数用来根据 URL 获取站点的标题（假设使用 fetch 或其他方式）
const getFavicon = async (url) => {
  let faviconUrl: any = null;
  try {
    // 先请求目标页面的 HTML 内容
    const response = await fetch(url);
    const html = await response.text();

    // 使用正则匹配获取 favicon
    const faviconMatch =
      html.match(/<link rel="icon" href="(.*?)"/i) ||
      html.match(/<link rel="shortcut icon" href="(.*?)"/i);

    if (faviconMatch) {
      const faviconUrl2 = faviconMatch[1];
      // 如果是相对路径，需要将其转化为绝对路径
      if (!faviconUrl2.startsWith("http")) {
        const baseUrl = new URL(url);
        faviconUrl = new URL(faviconUrl2, baseUrl.origin).href;
      } else {
        faviconUrl = faviconUrl2;
      }
    } else {
      // 如果没有找到，使用默认的 favicon
      faviconUrl = `${new URL(url).origin}/favicon.ico`;
    }
    return faviconUrl;
  } catch (error) {
    console.error("获取 favicon 失败:", error);
    faviconUrl = "/path/to/default/favicon.ico"; // 设置默认图标
    return faviconUrl;
  }
};
</script>

<style lang="css" scoped>
.card-link-wrapper {
  border: 1px solid #ddd;
  padding: 10px;
  margin: 10px 0;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.card-link {
  text-decoration: none;
  color: inherit;
}

.card-content h3 {
  font-size: 18px;
  font-weight: bold;
}

.card-content p {
  color: #555;
}
</style>
